/* The FSquare global module. This contains variables and functions
 * used by various other areas of the site */
var FSquare = (function($) {
    
    function showFacetMultiselect(abbr) {
    	openModal('#facet-' + abbr);
    	
    }
    
    function updateCurrentImage() {
        //grab the active product option values
        var activeOptions = $('.product-options .active');
        var optionValues = [];
        $.each(activeOptions, function() {
            optionValues.push($(this).attr('data-product-option-value'));
        });
        var mediaItems = $('#product_thumbs a');
        var finalMedia;
        var finalMediaMatches = 0;
        $.each(mediaItems, function() {
            var candidateMedia = this;
            var candidateMediaMatches = 0;
            $.each(optionValues, function() {
                if ($(candidateMedia).attr('data-tags') != undefined && $(candidateMedia).attr('data-tags').toLowerCase().indexOf(this.toLowerCase()) !== -1) {
                    candidateMediaMatches++;
                }
            });
            if (candidateMediaMatches > finalMediaMatches) {
                finalMedia = candidateMedia;
                finalMediaMatches = candidateMediaMatches;
            }
        });
        
        //at this point I should have the best-matched media item; select it
        if (finalMedia != null) {
            finalMedia.click();
        }
    }
    
    function updatePriceDisplay() {
        var productOptions = getProductOptionData();

        var selectedProductOptions = [];

        for (var i = 0; i < productOptions.length; i++) {
            selectedProductOptions.push(productOptions[i].selectedValue); // add selected value to array
        }
        
        var productOptionPricing = getPricingData();
        
        var price;
        
        for (var i = 0; i < productOptionPricing.length; i++) {
            var pricing = productOptionPricing[i];
            if ($(pricing.selectedOptions).not(selectedProductOptions).length == 0 && $(selectedProductOptions).not(pricing.selectedOptions).length == 0) {
                price = pricing.price;
                break;
            }
        }
        
        if (price) {
            $price = $('#price div');
            if ($price.length != 0) {
                $price.text(price);
            } else {
                $('.product-options.modal:visible ul').first().append('<div id="price"><div>' + price + '</div></div>');
            }
            $('#price div').text(price);
        }
        
    }
    
    var showNotificationTimer;
    function showNotification(notification, delay) {
    	clearTimeout(showNotificationTimer);
        if (!delay) {
            delay = '3500';
        }
        var notificationBar = $('#notification_bar');
        notificationBar.html(notification);
        if(notificationBar.is(':visible')){
        	notificationBar.css('display','block');
        	notificationBar.delay(delay);
        }else{
        	notificationBar.slideToggle('slow');
        }
        showNotificationTimer = setTimeout("$('#notification_bar').slideToggle('slow')",delay);
        
    }
    
    function changeProductOption($option) {
        if (!$option.is('.active')) {
            $option.siblings('.active').removeClass('active');
            $option.toggleClass('active');
            var selectedOption = $option.data('product-option-value');
            var $optionText = $option.parents('.product-option-group').find('span.option-value');
            $optionText.text(selectedOption.valueName);
            var productOptionData = getProductOptionData();

            for (var i = 0; i < productOptionData.length; i++) {
                var option = productOptionData[i];
                if (option.id === selectedOption.optionId) {
                    option.selectedValue = selectedOption.valueId;
                    break;
                }
            }
            
            updateCurrentImage();
            updatePriceDisplay();
        }
    }
    
    function getProductOptionData() {
        return $('#product-option-data').data('product-options');
    }
    
    function getPricingData() {
        return $('#product-option-data').data('product-option-pricing');
    }

    function updateLocaleSelection(){
        var locale = $('span#selectedLocale').text();
        $("#" + locale).addClass('selected');
    }
    
    
    
    function showLoading(){
    	$('.window-overlay').fadeIn(0);
    }
    
    
    function openModal(selector, appendToBody, callback, closeCallback){
    	
    	var close = $("<a href='javascript:;' class='close-window'>×</a>");
    	close.on('click', function(){
    		var that = $(this);
    		var wind = that.parent('.window');
    		wind.fadeOut(200, function(){
    			that.remove();
    			wind.removeClass('window');
        		$('.window-overlay').fadeOut(100);
        		if(closeCallback)
        			closeCallback();
        	});
    	});
    	
    	var element = $(selector);
    	
    	
    	element.append(close);
    	element.addClass('window');
    	$('.window-overlay').fadeIn(100, function(){
    		
    		if(appendToBody)
        		$('body').append(element);
    		
    		var height = element.height();
        	var width = element.width();
    		
        	var marginLeft = width/2;
        	var marginTop = (height/2)+100;
        	
        	element.css('marginLeft', '-'+marginLeft+"px");
        	element.css('marginTop', '-'+marginTop+"px");
        	
        	
    		element.fadeIn(200);
    		element.draggable();
    		if(callback)
    			callback();
    	});
    }
    
    function addViewedProduct(product){
    	var MAX_ITEMS = 10;
    	//localStorage.removeItem("lastViewdProducts");
//    	var index = product.productId;
    	var lastViewdProductsString = localStorage.lastViewdProducts;
    	if(!lastViewdProductsString)
    		lastViewdProductsString = '{"products":[]}';
    	var lastViewdProductsJson = JSON.parse(lastViewdProductsString);
    	
    	var products = lastViewdProductsJson['products'];
    	var found = -1;
    	for(var i in products){
    		var prod = products[i];
    		if(prod.productId == product.productId){
    			found = i;
    			break;
    		}
    	}
    	if (found > -1) {
    		products.splice(found, 1);
    	}
    	
    	products.push(product);
    	if(product.length > MAX_ITEMS)
    		products.splice(0, 1);
    	
    	lastViewdProductsJson['products'] = products;
    	localStorage.setItem("lastViewdProducts", JSON.stringify(lastViewdProductsJson));
    }
    
    function showViewedProducts(){
    	console.log("Context: "+BASE_URL);
    	var wrapper = $("#last-viewed");
    	if(wrapper.length < 1)
    		return;
    	
    	var lastViewdProductsString = localStorage.lastViewdProducts;
    	if(!lastViewdProductsString)
    		return;
    	
    	var lastViewdProductsJson = JSON.parse(lastViewdProductsString);
    	var products = lastViewdProductsJson['products'];
    	var lastViewed = '<span class="title" th:text="#{product.last.viewed.products}">Last viewed products</span><ul id="last_viewed_products" class="last_viewed_products group">';
    	var length = products.length;
    	for(var i in products){
    		var product = products[i];
    		
    		var prd = '<li class="simple_product_container" '+ ((length<6 && i > 0)?'style="margin-left: 70px;"':'')+'>';
    		prd += '<a href="'+BASE_URL+product['url']+'">';
    		prd += '<img width="120px" src="'+BASE_URL+product['image']+'"/>';
    		prd += '<div class="simple_product_name">'+product['name']+'</div>';
    		prd += '</a>';
    		prd += '</li>';
    		
    		lastViewed += prd;
    		console.log(prd);
    	}
    	
    	lastViewed += '</ul><div class="clearfix"></div>';
    	lastViewed += '<a href="javascript:;" class="clear_viewed_products" onclick="FSquare.clearViewedProducts()"><i class="fa fa-times"></i> clear viewed products</a>';
    	lastViewed += '<div class="clearfix"></div>';
    	
    	wrapper.show();
    	wrapper.append(lastViewed);
    	if(length > 5){
    		$("#last_viewed_products").flexisel({visibleItems: 5});
    	}
    		
    	
    }
    
    function clearViewedProducts(){
    	$("#last-viewed").hide();
    	localStorage.removeItem("lastViewdProducts");
    }
    
    function setBaseUrl(url){
    	var length = url.length;
    	BASE_URL = url.substr(0,length-1);
    }
    
    var BASE_URL = "";
    return {
        showNotification : showNotification,
        changeProductOption : changeProductOption,
        showFacetMultiselect : showFacetMultiselect,
        showLoading : showLoading,
        getProductOptionData : getProductOptionData,
        updateLocaleSelection: updateLocaleSelection,
        openModal:openModal,
        addViewedProduct:addViewedProduct,
        showViewedProducts:showViewedProducts,
        clearViewedProducts:clearViewedProducts,
        setBaseUrl: setBaseUrl,
        BASE_URL:BASE_URL
    };
})($);